package com.zsc.wxm.ysh.anjo.house.utils;

import com.zsc.wxm.ysh.anjo.house.mapper.SquenceMapper;
import com.zsc.wxm.ysh.anjo.house.model.Squence;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * 描述：编码生成器
 *
 * @author playmaker
 * @since 2021/3/7 10:24
 */
@Component
public class CodeUtil {

    @Resource
    private SquenceMapper squenceMapper;

    /**
     * 生成房源编号
     *
     * @return
     */
    public String getSquenceCode() {
        //4 + 16 位
        StringBuilder stringBuilder = new StringBuilder();
        //前缀
        stringBuilder.append("ANJO");
        //1、前8位为时间信息
        LocalDateTime now = LocalDateTime.now();
        //把当前日期的"-"替换掉
        String nowDate = now.format(DateTimeFormatter.ISO_DATE).replace("-", "");
        stringBuilder.append(nowDate);
        //2、中间6位为自增序列
        int count = 0;
        Squence squence = squenceMapper.selectById(1L);
        //获取当前值
        count = squence.getCurrentValue();
        squence.setCurrentValue(count + squence.getStep());
        squenceMapper.updateById(squence);

        String sequenceStr = String.valueOf(count);

        //凑足6位,后面补0
        for (int i = 0; i < 6 - sequenceStr.length(); i++) {
            stringBuilder.append(0);
        }
        stringBuilder.append(sequenceStr);
        //3、最后默认为00
        stringBuilder.append("00");
        return stringBuilder.toString();
    }
}
